﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using FeedAgregator;
using System.Web.UI.HtmlControls;
using System.Reflection;
using System.Text;
using DDNY.WebPortals.Common;
using System.Data;
using System.Text.RegularExpressions;

public partial class _Default : System.Web.UI.Page
{
    public int CategoryId { get; set; }

    public int PageNumber { get; set; }

    public int FeedId { get; set; }

    public string TagName { get; set; }

    public string SearchWord { get; set; }

    public int SearchType { get; set; }

    public int SelectedListViewIndex
    {
        get
        {
            if (Session["SelectedListViewIndex"] != null)
            {
                return (int)Session["SelectedListViewIndex"];
            }
            else
            {
                return 0;
            }
        }

        set
        {
            Session["SelectedListViewIndex"] = value;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {
            SelectedListViewIndex = 0;
            //
            SetCanonicalUrlMetaTag();
        }
        foreach (string key in Request.QueryString)
        {
            switch (key.ToLower())
            {
                case "category":
                    CategoryId = int.Parse(Request.QueryString[key]);
                    break;
                case "page":
                    PageNumber = int.Parse(Request.QueryString[key]);
                    break;
                case "feedid":
                    FeedId = int.Parse(Request.QueryString[key]);
                    break;
                case "tag":
                    TagName = Request.QueryString[key];
                    break;
                case "search":
                    SearchWord = Request.QueryString[key];
                    break;
                case "type":
                    SearchType = int.Parse(Request.QueryString[key]);
                    break;

                default:
                    break;
            }
        }
        if (CategoryId != 0)
        {
            FeedItemsDataSource.Where = "Feed.CategoryId==" + CategoryId.ToString();
        }
        else if (FeedId > 0)
        {
            FeedItemsDataSource.Where = @"Feed.ID=={0}";
            FeedItemsDataSource.Where = string.Format(FeedItemsDataSource.Where, FeedId.ToString());
        }
        else if (!string.IsNullOrEmpty(TagName))
        {
            FeedItemsDataSource.Where = @"Title.Contains(""{0}"")";
            FeedItemsDataSource.Where = string.Format(FeedItemsDataSource.Where, TagName);
            Timer1.Enabled = false;
        }
        else if (!string.IsNullOrEmpty(SearchWord))
        {
            Timer1.Enabled = false;
            if (SearchType == 0)
            {
                //търсене само в title
                FeedItemsDataSource.Where = @"Title.Contains(""{0}"")";
            }
            else
            {
                FeedItemsDataSource.Where = @"Title.Contains(""{0}"") || ItemContent.Contains(""{0}"")";
            }

            FeedItemsDataSource.Where = string.Format(FeedItemsDataSource.Where, SearchWord);
        }

        else
        {
            FeedItemsDataSource.Where = "";
        }
        if (!IsPostBack)
        {
            GenerateTitle(CategoryId, FeedId, PageNumber);
            Timer1_Tick(sender, e);

        }
        LastUpdatedLable.Text = "Последна актуализация " + DateTime.Now.ToString("HH:mm:ss");

    }

    private void SetCanonicalUrlMetaTag()
    {
        if (Request.Url.AbsoluteUri.EndsWith("default.aspx"))
        {
            HtmlLink canonicalRelLink = new HtmlLink();
            canonicalRelLink.Attributes.Add("rel", "canonical");
            canonicalRelLink.Href = ("http://bgsignal.com/");
            Header.Controls.Add(canonicalRelLink);
        }
    }

    private void GenerateTitle(int categoryId, int feedId, int pageNumber)
    {
        string categoryName;
        if (categoryId == 0)
        {
            if (FeedId > 0)
            {
                Feed currentFeed = DataAccessHelper.GetFeedByID(feedId);

                categoryName = DataAccessHelper.GetCategoryTitleById(currentFeed.CategoryID) + " от " + currentFeed.DisplayName;
            }
            else if (!string.IsNullOrEmpty(TagName))
            {
                categoryName = "Таг " + TagName;
            }

            else
            {
                categoryName = "Всичко от българските форуми";
            }
        }
        else
        {
            categoryName = DataAccessHelper.GetCategoryTitleById(categoryId);
        }
        if (pageNumber > 0)
        {
            this.Title = categoryName + " - страница " + pageNumber.ToString();
        }
        else
        {
            this.Title = categoryName;
        }
        if (SearchWord != null)
        {
            this.Title = SearchWord.ToUpper() + " - Резултат от търсене в заглавие";
            if (SearchType > 0)
            {
                this.Title += " и съдържание";
            }
        }

    }

    protected void Timer1_Tick(object sender, EventArgs e)
    {
        FeedItemsListView.DataBind();
    }

    protected void FeedItemsListView_ItemDataBound(object sender, ListViewItemEventArgs e)
    {
        if (e.Item.ItemType == ListViewItemType.DataItem)
        {
            ListViewDataItem dataItem = e.Item as ListViewDataItem;
            object feedItem = dataItem.DataItem;
            DateTime pubDate;
            Type feedItemDynamicType = feedItem.GetType();
            PropertyInfo itemUrlPropertyInfo = feedItemDynamicType.GetProperty("PubDate");
            pubDate = (DateTime)itemUrlPropertyInfo.GetValue(feedItem, null);
            Label PubDateLabel = e.Item.FindControl("PubDateLabel") as Label;
            string formatDateString = ("dd.MM - HH:mm");
            if (pubDate.Date == DateTime.Now.Date)
            {
                formatDateString = ("HH:mm");
            }
            PubDateLabel.Text = pubDate.ToString(formatDateString);

        }

    }
    protected void FeedItemsListView_SelectedIndexChanged(object sender, EventArgs e)
    {

    }
    protected void FeedItemsListView_DataBound(object sender, EventArgs e)
    {
        if (FeedItemsListView.Items.Count > 0)
        {
            int feedItemID = int.Parse(FeedItemsListView.DataKeys[SelectedListViewIndex].Value.ToString());
            FeedItem feedItem = DataAccessHelper.GetFeedItemByID(feedItemID);
            HtmlContainerControl ItemContentDiv = FeedItemsListView.Items[SelectedListViewIndex].FindControl("ItemContentDiv") as HtmlContainerControl;
            if (feedItem.ItemContent != null)
            {
                feedItem.ItemContent = CommonUtils.SanitizeContent(feedItem.ItemContent, true);
                if (feedItem.ItemContent.Length > 2000)
                {
                    ItemContentDiv.InnerHtml = feedItem.ItemContent.Substring(0, 800);
                }
                else
                {
                    ItemContentDiv.InnerHtml = feedItem.ItemContent;
                }
            }

            ItemContentDiv.Visible = true;
        }
    }

    protected void FeedItemsListView_SelectedIndexChanging(object sender, ListViewSelectEventArgs e)
    {
        SelectedListViewIndex = e.NewSelectedIndex;
    }
}
